import functools

from werkzeug.datastructures import MultiDict
from flask import request, jsonify
from app.response import ResponseCode, error_json


def validate_form(form_class):
    def decorator(view_func):
        @functools.wraps(view_func)
        def inner(*args, **kwargs):
            if request.method == 'GET':
                formdata = request.args
            else:
                if request.json:
                    formdata = MultiDict(request.json)
                else:
                    formdata = request.form

            form = form_class(formdata=formdata)
            if not form.validate():
                return error_json(errcode=ResponseCode.PARAMETER_ERROR, errmsg=form.errors)
            return view_func(*args, **kwargs)

        return inner

    return decorator
